<template>
  <div class="timestamp-tool module-container">
    <div class="module-header">
      <h2>时间戳转换</h2>
      <p class="module-description">Unix时间戳与日期时间相互转换工具</p>
    </div>

    <div class="module-content">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="card">
            <h3>时间戳转日期</h3>
            <el-form label-width="100px">
              <el-form-item label="时间戳">
                <el-input
                  v-model="timestamp"
                  placeholder="输入时间戳（秒或毫秒）"
                  @input="convertFromTimestamp"
                >
                  <el-button slot="append" @click="useCurrentTimestamp">当前</el-button>
                </el-input>
              </el-form-item>
              
              <el-form-item label="单位">
                <el-radio-group v-model="timestampUnit" @change="convertFromTimestamp">
                  <el-radio label="second">秒</el-radio>
                  <el-radio label="millisecond">毫秒</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="结果">
                <el-input v-model="dateFromTimestamp" readonly>
                  <el-button slot="append" icon="el-icon-copy-document" @click="copyResult(dateFromTimestamp)"></el-button>
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-col>

        <el-col :span="12">
          <div class="card">
            <h3>日期转时间戳</h3>
            <el-form label-width="100px">
              <el-form-item label="日期时间">
                <el-date-picker
                  v-model="dateTime"
                  type="datetime"
                  placeholder="选择日期时间"
                  @change="convertToTimestamp"
                  style="width: 100%"
                />
              </el-form-item>
              
              <el-form-item label="时间戳(秒)">
                <el-input v-model="timestampInSeconds" readonly>
                  <el-button slot="append" icon="el-icon-copy-document" @click="copyResult(timestampInSeconds)"></el-button>
                </el-input>
              </el-form-item>
              
              <el-form-item label="时间戳(毫秒)">
                <el-input v-model="timestampInMilliseconds" readonly>
                  <el-button slot="append" icon="el-icon-copy-document" @click="copyResult(timestampInMilliseconds)"></el-button>
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>

      <div class="card" style="margin-top: 20px">
        <h3>常用时间格式</h3>
        <el-table :data="timeFormats" style="width: 100%">
          <el-table-column prop="format" label="格式" width="200" />
          <el-table-column prop="example" label="示例" />
          <el-table-column prop="description" label="说明" />
          <el-table-column width="80">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="copyResult(scope.row.example)">
                复制
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Timestamp',
  data() {
    const now = new Date()
    return {
      timestamp: '',
      timestampUnit: 'second',
      dateFromTimestamp: '',
      dateTime: now,
      timestampInSeconds: Math.floor(now.getTime() / 1000).toString(),
      timestampInMilliseconds: now.getTime().toString(),
      timeFormats: []
    }
  },
  created() {
    this.updateTimeFormats()
    setInterval(() => {
      this.updateTimeFormats()
    }, 1000)
  },
  methods: {
    convertFromTimestamp() {
      if (!this.timestamp) {
        this.dateFromTimestamp = ''
        return
      }
      
      try {
        const ts = parseInt(this.timestamp)
        const date = new Date(this.timestampUnit === 'second' ? ts * 1000 : ts)
        
        if (isNaN(date.getTime())) {
          this.dateFromTimestamp = '无效的时间戳'
        } else {
          this.dateFromTimestamp = this.formatDate(date)
        }
      } catch (e) {
        this.dateFromTimestamp = '转换失败'
      }
    },
    
    convertToTimestamp() {
      if (!this.dateTime) {
        this.timestampInSeconds = ''
        this.timestampInMilliseconds = ''
        return
      }
      
      const ts = this.dateTime.getTime()
      this.timestampInSeconds = Math.floor(ts / 1000).toString()
      this.timestampInMilliseconds = ts.toString()
    },
    
    useCurrentTimestamp() {
      const now = Date.now()
      this.timestamp = this.timestampUnit === 'second' 
        ? Math.floor(now / 1000).toString()
        : now.toString()
      this.convertFromTimestamp()
    },
    
    formatDate(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    
    updateTimeFormats() {
      const now = new Date()
      this.timeFormats = [
        {
          format: 'ISO 8601',
          example: now.toISOString(),
          description: '国际标准格式'
        },
        {
          format: 'RFC 2822',
          example: now.toUTCString(),
          description: 'HTTP协议日期格式'
        },
        {
          format: 'Unix时间戳(秒)',
          example: Math.floor(now.getTime() / 1000).toString(),
          description: '从1970-01-01开始的秒数'
        },
        {
          format: 'Unix时间戳(毫秒)',
          example: now.getTime().toString(),
          description: '从1970-01-01开始的毫秒数'
        },
        {
          format: '本地时间',
          example: now.toLocaleString(),
          description: '本地化的日期时间格式'
        }
      ]
    },
    
    copyResult(text) {
      if (!text) return
      
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('已复制到剪贴板')
      }).catch(() => {
        this.$message.error('复制失败')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.timestamp-tool {
  .card {
    background: #fff;
    border-radius: 8px;
    padding: $spacing-large;
    box-shadow: $box-shadow-light;
    
    h3 {
      margin-top: 0;
      margin-bottom: $spacing-medium;
      color: $text-primary;
    }
  }
  
  .module-content {
    padding: $spacing-large;
  }
}
</style>